package com.Login.web;

import com.Base.BaseServlet;
import com.Base.ResultCode;
import com.Business.service.OrganizationService;
import com.Login.Service.LoginService;
import com.Pojo.Organization;
import com.Pojo.User;
import com.Utils.PWDUtil;
import com.Utils.RedisUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by XingYang on 2019/2/26.
 */
@Controller
@RequestMapping(value = "login.spr")
public class LoginController extends BaseServlet {
    @Autowired
    LoginService loginService;
    RedisUtil redisUtil = new RedisUtil();
    PWDUtil pwdUtil = new PWDUtil();

    @RequestMapping(params = "method=login")
    @ResponseBody
    public String doLogin(@RequestParam String username, @RequestParam String password,HttpServletRequest request){

        RedisUtil re = new RedisUtil();
        SecurityUtils.setSecurityManager(securityManager);
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken auth = new UsernamePasswordToken(username,pwdUtil.encodeBase64(password));
        HashMap<String, String> resp = new HashMap<>();
        HttpSession session = request.getSession();
        session.setAttribute("username",username);
        try{
            currentUser.login(auth);
            log.info("用户\t"+username+"\t登录成功");
            resp.put("result",ResultCode.SUCCESS);
            resp.put("msg","success");
            Jedis jedis = re.getClient();
            User user = (User)re.unSerializseObj(jedis.lrange(username.getBytes(),0,0).get(0));
            session.setAttribute("user",user);
            resp.put("username",user.getNickname());

            return JSONUtils.toJSONString(resp);
        }catch (UnknownAccountException uae){
            log.info("用户\t"+username+"\t尝试登录失败");
            resp.put("result",ResultCode.UnkonwUser);
            resp.put("msg","该用户不存在");
            return JSONUtils.toJSONString(resp);
        }catch (IncorrectCredentialsException ice){
            log.info("用户\t"+username+"\t尝试登录失败");
            resp.put("result",ResultCode.UserNamePassWordError);
            resp.put("msg","用户名或密码错误");
            return JSONUtils.toJSONString(resp);
        }catch (LockedAccountException lae){
            log.info("用户\t"+username+"\t尝试登录失败");
            resp.put("result",ResultCode.AccountLocked);
            resp.put("msg","该账号已被锁定！");
            return JSONUtils.toJSONString(resp);
        }

    }
    @RequestMapping(value = "logout")
    @ResponseBody
    public String logout(){

        HashMap<String, String> resp = new HashMap<>();
        resp.put("result",ResultCode.SUCCESS);
        resp.put("msg","注销成功！");
        return JSONUtils.toJSONString(resp);
    }


    @Autowired
    OrganizationService organizationService;
    @RequestMapping(params = "method=regsist" )
    @ResponseBody
    public String regsist(@RequestParam String username,@RequestParam String password,@RequestParam String companyaccount){
        HashMap<String, String> resp = new HashMap<>();
        if(username==""||password==""||companyaccount==""){
            resp.put("result",ResultCode.NullArguments);
            resp.put("msg","未传入有效的参数！");
            return JSONUtils.toJSONString(resp);
        }
        Organization organization = null;
        organization = organizationService.getOrganizationByAccount(companyaccount);
        if(organization == null){
            resp.put("result",ResultCode.UnkonwUser);
            resp.put("msg","错误的主账号！");
            return JSONUtils.toJSONString(resp);
        }

        try{
            User user = new User();
            user.setUsername(username);
            user.setPassword(PWDUtil.encodeBase64(password));
            user.setMainaccount(organization.getId());//数据库存入组织id
            loginService.addUser(user);
            resp.put("result",ResultCode.SUCCESS);
            resp.put("msg","注册成功！");
        }catch (Exception e){
            resp.put("result",ResultCode.UserExists);
            resp.put("msg","该用户名已存在");
            e.printStackTrace();
        }
        return JSONUtils.toJSONString(resp);

    }
    @RequestMapping(params = "method=refreshAllUser")
    @ResponseBody
    public String refreshAllUser(){
        List<User> userList = loginService.getAllUser();
        for(User user : userList){
            loginService.refreshUser(user.getUsername());
        }


        return sendResponse(ResultCode.SUCCESS,"",null);
    }

    @RequestMapping(params = "method=refreshUser")
    @ResponseBody
    public String refreshUser(@RequestParam String username, HttpServletRequest request){
        HashMap<String, String> resp = new HashMap<>();
        try{
            if(username==""||username==null){
                HttpSession session =  request.getSession();
                username = (String) session.getAttribute("username");
            }
        }catch (NullPointerException e){
            resp.put("result",ResultCode.NullArguments);
            resp.put("msg","无效操作！");
            return JSONUtils.toJSONString(resp);
        }
        if(loginService.refreshUser(username)){
            resp.put("result",ResultCode.SUCCESS);
            resp.put("msg","刷新用户权限成功！");
        }else{
            resp.put("result",ResultCode.Failed);
            resp.put("msg","刷新用户权限失败！");
        }


        return JSONUtils.toJSONString(resp);

    }
    @RequestMapping(value = "getRoles")
    @ResponseBody
    public String getRoles(HttpServletRequest request){
        HttpSession session = request.getSession();
        User user  = (User) session.getAttribute("user");
        PageHelper.startPage(request);
        List<String> list = loginService.getRolesByUid(user.getId());
        PageInfo<String> pageInfo = new PageInfo<>(list);

        return sendPageResponse(ResultCode.SUCCESS,"succcess",pageInfo);

    }
    @RequestMapping(value = "getPowers")
    @ResponseBody
    public String getPowers(HttpServletRequest request){
        HttpSession session = request.getSession();
        User user  = (User) session.getAttribute("user");
        Map map = new HashMap();
        map.put("powers",user.getPowers());
        map.put("roles",user.getRoles());
        return sendResponse(ResultCode.SUCCESS,"success",map);
    }
    @RequestMapping(params = "method=flushKey")
    @ResponseBody
    public String flushRedisKey(@RequestParam String key){
        if(StringUtils.isEmpty(key)){
            return sendResponse(ResultCode.NullArguments,"参数错误！",null);
        }
        if(0==loginService.delRedisKey(key))
        {
            return sendResponse(ResultCode.Message,"未命中key",null);
        }
        return sendResponse(ResultCode.SUCCESS,"",null);
    }

}
